﻿using System.Threading.Tasks;
using CAPDemo.BasketService.Models;
using CAPDemo.Events;
using DotNetCore.CAP;
using Microsoft.EntityFrameworkCore;

namespace CAPDemo.BasketService.Handlers
{
    public class UserAddressUpdateEventHandler : IEventHandler<UserAddressUpdatedEvent>, ICapSubscribe
    {
        private readonly BasketDbContext _dbContext;

        public UserAddressUpdateEventHandler(BasketDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        [CapSubscribe(nameof(UserAddressUpdatedEvent))]
        public async Task Handler(UserAddressUpdatedEvent eventData)
        {
            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                var basket = await _dbContext.Baskets.FirstAsync(b => b.UserId == eventData.Id);
                basket.Address = eventData.Address;
                await _dbContext.SaveChangesAsync();

                transaction.Commit();
            }
        }
    }
}
